package cn.echase.ecare.yinfayun.utils;

import com.github.pagehelper.PageInfo;
import org.dromara.common.mybatis.core.page.TableDataInfo;

import java.util.ArrayList;
import java.util.List;

/**
 * 分页
 */
public class PageUtil {

    public static <T> PageInfo getResultPageInfoList(List<T> resultList, int pageNum, int pageSize) {
        int startIndex;
        int endIndex;
        int totalCount = resultList.size();
        int pageCount = (int) Math.ceil(totalCount * 1.0 / pageSize);
        PageInfo<T> pageResult;

        //最后一页
        if (pageNum == pageCount) {
            startIndex = (pageNum - 1) * pageSize;
            endIndex = totalCount;
            pageResult = new PageInfo<>(resultList.subList(startIndex, endIndex));
        } else if (pageNum < pageCount) {
            startIndex = (pageNum - 1) * pageSize;
            endIndex = pageNum * pageSize;
            pageResult = new PageInfo<>(resultList.subList(startIndex, endIndex));
        } else {
            pageResult = new PageInfo<>(new ArrayList<>());
        }

        pageResult.setPages(pageCount);
        pageResult.setTotal(totalCount);
        pageResult.setPageNum(pageNum);
        pageResult.setPageSize(pageSize);
        return pageResult;
    }

    public static <T> TableDataInfo getResultTableDataInfoList(List<T> resultList, int pageNum, int pageSize) {
        int startIndex;
        int endIndex;
        int totalCount = resultList.size();
        int pageCount = (int) Math.ceil(totalCount * 1.0 / pageSize);
        TableDataInfo<T> pageResult;

        //最后一页
        if (pageNum == pageCount) {
            startIndex = (pageNum - 1) * pageSize;
            endIndex = totalCount;
            pageResult = TableDataInfo.build(resultList.subList(startIndex, endIndex));
        } else if (pageNum < pageCount) {
            startIndex = (pageNum - 1) * pageSize;
            endIndex = pageNum * pageSize;
            pageResult = TableDataInfo.build(resultList.subList(startIndex, endIndex));
        } else {
            pageResult = TableDataInfo.build(new ArrayList<>());
        }

        pageResult.setTotal(totalCount);
        return pageResult;
    }

}
